//
// Created by Administrator on 2018/10/22.
//
#import <malloc.h>
#import <string>
#include "StringUtils.h"

char *StringUtils::jstring2char(JNIEnv *env, jstring jstr) {

    char *rtn = nullptr;
    jclass  strClz  = env->FindClass("java/lang/String");
    jstring strEncode = env->NewStringUTF("UTF-8");
    jmethodID mid = env->GetMethodID(strClz, "getBytes", "(Ljava/lang/String;)[B");
    jbyteArray  byteAarry = static_cast<jbyteArray>(env->CallObjectMethod(jstr, mid, strEncode));
    //jsize <- jint <- int32_t
    jsize length = env->GetArrayLength(byteAarry);
    jbyte *jbyte1 = env->GetByteArrayElements(byteAarry, JNI_FALSE);
    if (length > 0){

        //size_t是标准C库中定义的，应为unsigned int，在64位系统中为 long unsigned int。
        size_t len = static_cast<size_t>(length + 1);
        //申请内存
        rtn  = static_cast<char *>(malloc(len));

        //将字符复制到rtn
        memcpy(rtn, jbyte1, len);

        //添加结束字符
        rtn[len] = 0;

    }

    env->ReleaseByteArrayElements(byteAarry, jbyte1, 0);


    return rtn;
}

char *StringUtils::toHexString(JNIEnv *env, jbyteArray jba) {


    jsize array_size = env->GetArrayLength(jba);
    jbyte  *sha1 = env->GetByteArrayElements(jba, JNI_FALSE);
    char *hex_sha = new char[array_size*2 +1];

    jsize hexLength = strlen(HexCode);

    for (int i = 0; i < array_size; ++i) {
        hex_sha[2 * i] = HexCode[((unsigned char) sha1[i]) / hexLength];
        hex_sha[2 * i + 1] = HexCode[((unsigned char) sha1[i]) % hexLength];
    }

    hex_sha[array_size * 2] = '\0';
    return hex_sha;
}

jstring StringUtils::char2jstring(JNIEnv *env, const char *pat) {

    //定义java String类 strClass
    jclass strClass = (env)->FindClass("Ljava/lang/String;");
    //获取String(byte[],String)的构造器,用于将本地byte[]数组转换为一个新String
    jmethodID ctorID = (env)->GetMethodID(strClass, "<init>", "([BLjava/lang/String;)V");
    //建立byte数组
    jbyteArray bytes = (env)->NewByteArray(strlen(pat));
    //将char* 转换为byte数组
    (env)->SetByteArrayRegion(bytes, 0, strlen(pat), (jbyte *) pat);
    // 设置String, 保存语言类型,用于byte数组转换至String时的参数
    jstring encoding = (env)->NewStringUTF("UTF-8");
//    jstring encoding = (env)->NewStringUTF("GB2312");
    //将byte数组转换为java String,并输出
    return (jstring) (env)->NewObject(strClass, ctorID, bytes, encoding);

}
